package com.gxuwz.medical.web.servlet;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.gxuwz.medical.dao.ChronicdisApplyDao;
import com.gxuwz.medical.dao.PolicyDao;
import com.gxuwz.medical.domain.chronicdisApply.ChronicdisApply;
import com.gxuwz.medical.domain.policy.Policy;
import com.gxuwz.medical.exception.DbException;
import com.gxuwz.medical.tools.TimeUtils;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;



public class ChronicdisApplyServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String m = request.getParameter("m");
		
		if("list".equals(m)){
			process(request,response,"/page/chronicdisApply/chronicdisApply_open.jsp");
		}else if("check".equals(m)){
			check(request,response);
		}else if("add".equals(m)){
			try {
				add(request,response);
				process(request,response,"/page/chronicdisApply/chronicdisApply_show.jsp");
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}else if("tlist".equals(m)){
			process(request,response,"/page/chronicdisApply/chronicdisApply_show.jsp");
		}else if("Excel".equals(m)){
			try {
				createExcel(request, response);
			} catch (DbException e) {
				e.printStackTrace();
			}	
		}
		
	}
	
	/**
	 * 返回给前端可报销金额
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	private void check(HttpServletRequest request, HttpServletResponse response) throws IOException{
		response.setContentType("text/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		Map<String,Object>mapList = new HashMap<String, Object>();
		String amountApply = request.getParameter("mhcx");
		String idcard = request.getParameter("idcard");
		
		ChronicdisApplyDao chronicdisApplyDao = new ChronicdisApplyDao();
		Double count = chronicdisApplyDao.count(idcard);    //统计依据报销过的金额
		PolicyDao policyDao = new PolicyDao();
		Policy policy = policyDao.queryPolicy();
		Double rate = Double.parseDouble(policy.getRate());
//		System.out.println("rate:"+rate);
		Double canApply = rate*Double.parseDouble(amountApply);//本次可报销的金额
//		System.out.println("canApply："+canApply);
		Double canBao = policy.getPlimit()-count;           //还可以报销的金额=报销限额-已报销过的金额
		if(canBao>0){  //还可以报销多钱
			if(canBao>=canApply){ //可以报销的金额是否大于前端传过来可以报销的金额
				mapList.put("state", 1);
				mapList.put("canApply",canApply);
			}else{
				mapList.put("state", 0);
				mapList.put("yiApply", count); //已经报销了
				mapList.put("canApply", canBao);  //还可以报销金额
				mapList.put("applyMoney",Math.floor(canBao/Double.parseDouble(policy.getRate()))); //最大可报销金额
			}
		}else{
			mapList.put("state", 3); //已达到上限
		}
	
		Gson gson = new Gson();
		String json = gson.toJson(mapList);
//		System.out.println(json);
		out.println(json);
		out.flush();
		out.close();
	}
	
	private void add(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException{
		String name = request.getParameter("name");
		String idcard = request.getParameter("idcard");
		String chronicname = request.getParameter("chronicname");
		String applyAcount = request.getParameter("applyAcount");
		System.out.println("applyAcount:"+applyAcount);
		ChronicdisApply ca = new ChronicdisApply(idcard,name,new BigDecimal(applyAcount),TimeUtils.formatDate(new Date()),chronicname);

		ca.add();
		
	}
	
	 // 导出Excel
	 private void createExcel(HttpServletRequest req, HttpServletResponse response) throws IOException, DbException {
		 
		  String[] tableHeaders={"身份证号","已报销金额","用户姓名","疾病编码","创建时间"};
			
		    // 1:创建一个workbook  
		    HSSFWorkbook workbook = new HSSFWorkbook();
		    HSSFSheet sheet = workbook.createSheet("Sheet1");
		    
		    // 2:设置每一列的宽度
		    sheet.setDefaultColumnWidth(20);  
	        sheet.setColumnWidth(0,5120);
	        sheet.setColumnWidth(1,5120);
	        sheet.setColumnWidth(2,5120);
	        sheet.setColumnWidth(3,5120);
	        sheet.setColumnWidth(4,5120);

		    // 3:创建头部样式  
	        HSSFCellStyle cellStyle = workbook.createCellStyle();    
	        Font font = workbook.createFont();
		    //font.setColor(HSSFColor.BLACK.index);  
		    cellStyle.setFont(font);
		    cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);  //水平居中
	//	    cellStyle.setVerticalAlignment(cellStyle.getVerticalAlignmentEnum().CENTER); // 垂直居中 
		    
		    // 4:创建文件体样式
	        HSSFCellStyle style1 = workbook.createCellStyle();  
	        style1.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中  
	 //       style1.setVerticalAlignment(style1.getVerticalAlignmentEnum().CENTER); // 垂直居中  
	        
		    // 5:将第一行的7个单元格给合并
		    sheet.addMergedRegion(new CellRangeAddress(0,0,0,4));  //四个参数分别代表  行开始 行结束 列开始 列结束
		    HSSFRow row = sheet.createRow(0); //创建第一行
		    row.setHeightInPoints(20);//设置行高
		    HSSFCell beginCell = row.createCell(0);
		    beginCell.setCellValue("慢性病报销统计单");  //赋值
		    beginCell.setCellStyle(cellStyle); //赋样式
		    
	        
	        
	        row = sheet.createRow(1);  //第二行
	        row.setHeightInPoints(20);//设置高度
		    // 创建表头
		    for (int i = 0; i < tableHeaders.length; i++) {
		        HSSFCell cell = row.createCell(i); //找到单元格
		        cell.setCellValue(tableHeaders[i]); //给单元格赋值
		        cell.setCellStyle(cellStyle);  
		    }
		    
		    ChronicdisApplyDao chronicdisApplyDao = new ChronicdisApplyDao();
		    List<ChronicdisApply>listApplySurface = chronicdisApplyDao.ChronicdisApplyList();
		    for(int i=0; i<listApplySurface.size();i++){
		    	int index = 0;
		    	row = sheet.createRow(i+2);  //行数累加
		    	row.setHeightInPoints(20);
		    	HSSFCell cell = row.createCell(index++); //找到这一行的每一列
		    	cell.setCellValue(listApplySurface.get(i).getIdcard());//赋值
		    	cell.setCellStyle(style1);
		    	HSSFCell cell1 = row.createCell(index++);
		    	cell1.setCellValue(listApplySurface.get(i).getApplyAcount().doubleValue());
		    	cell1.setCellStyle(style1);
		    	HSSFCell cell2 = row.createCell(index++);
		    	cell2.setCellValue(listApplySurface.get(i).getName());
		    	cell2.setCellStyle(style1);
		    	HSSFCell cell3 = row.createCell(index++);
		    	cell3.setCellValue(listApplySurface.get(i).getChronicname());
		    	cell3.setCellStyle(style1);
		    	HSSFCell cell4 = row.createCell(index++);
		    	cell4.setCellValue(listApplySurface.get(i).getCreatetime());
		    	cell4.setCellStyle(style1);
		    	
		    }
		    
		    OutputStream outputStream = response.getOutputStream();  //输出
		    response.reset(); 
		    response.setContentType("application/vnd.ms-excel");    //设置头部信息
		    response.setHeader("Content-disposition", "attachment;filename = ChronicdisApply.xls");

		    workbook.write(outputStream);
		    outputStream.flush();    
		    outputStream.close();
		    

	}
	

}
